package com.tanhua.server.controller;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class UserFreezeService {
    @Autowired
    private RedisTemplate<String,String>redisTemplate;

    /**
     * 判断用户是否背冻结，如果被冻结，则抛出异常
     * @param range 冻结范围
     * @param userId 用户id
     * */
    public void checkUserStatus(String range,Long userId){
        //1.拼接key，从redis查出数据
        String key = Constants.USER_FREEZE + userId;
        String value = redisTemplate.opsForValue().get(key);

        //2.如果数据存在，而且冻结范围一致，则抛出异常
        if(!StringUtils.isEmpty(value)){
            //将Json字符串转化为相应的对象
            Map map = JSON.parseObject(value, Map.class);
            String freezingRange = (String) map.get("freezingRange");
            if (range.equals(freezingRange)){
                throw new BusinessException(ErrorResult.error());
            }
        }
    }
}
